package com.qf.listener;

import com.google.gson.Gson;
import com.qf.entity.Goods;
import com.rabbitmq.client.Channel;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class EsQueueNamelistener {

    @Autowired
    private RestHighLevelClient client;

    @Value("${es.indexName}")
    private String indexName;

    @Value("${es.typeName}")
    private String typeName;

    @RabbitListener(queues = "${es.esQueueName}")
    public void addGoods(Goods goods, Channel channel, Message message) throws IOException {

        IndexRequest request = new IndexRequest(indexName, typeName);

        String json = new Gson().toJson(goods);

        request.source(json, XContentType.JSON);

        IndexResponse index = client.index(request, RequestOptions.DEFAULT);

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
